package com.nuanshui.heatedloan.credit.pay.behavior;

import com.aipg.common.AipgRsp;
import com.aipg.qtd.QTDRspDetail;
import com.aipg.transquery.QTDetail;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.credit.facade.AllinPayTransService;
import com.nuanshui.heatedloan.credit.pay.*;
import com.nuanshui.heatedloan.credit.pay.annotation.PayBehaviorAttribute;
import com.nuanshui.heatedloan.credit.pay.constant.OrderPayState;
import com.nuanshui.heatedloan.credit.pay.constant.PayBehaviorType;
import com.nuanshui.heatedloan.credit.pay.utils.AllinPayUtil;
import com.nuanshui.heatedloan.credit.pay.validation.ValidationResult;
import com.nuanshui.heatedloan.credit.pay.validation.ValidationResultCode;
import com.nuanshui.heatedloan.fund.facade.UserAccountBillService;
import com.nuanshui.heatedloan.fund.model.UserAccountBill;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 开始发送报文数据
 */
@PayBehaviorAttribute(value= PayBehaviorType.PaySuccessBehavior,order=401)
public class PaySuccessBehavior extends PayBehavior {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OrderPayStateService orderPayStateService;

    @Autowired
    private AllinPayTransService allinPayTransService;

    @Reference(url= GlobalParam.FUND_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version=GlobalParam.FUND_DUBBO_SERVER_VERSION)
    private UserAccountBillService userAccountBillService;

    private AllinPayResponse getBillDetail(PayRequest request)
    {
        if(PayContext.getContext().getTradeDetail()!=null)
        {
            return PayContext.getContext().getTradeDetail();
        }
        String payNum=PayContext.getContext().getPayNum();
        AllinPayResponse detail=allinPayTransService.queryTrade(payNum);

        AllinPayUtil.logOrderPay(logger, request, "通联支付结束确认 通联账单:"+ JSON.toJSONString(detail));

        return detail;
    }

    @Override
    public void internalInvoke(PayRequest request) {

        AllinPayUtil.logOrderPay(logger, request, "通联支付结束确认开始");

        AllinPayResponse response=getBillDetail(request);

        //如果已经处理过，此处直接结束
        if(response!=null) {
            QTDetail detail = response.getData();
            if (detail != null) {
                UserAccountBill bill = userAccountBillService.findSuccessAccountBillByPayNum(detail.getBATCHID());

                if (bill != null) {
                    AllinPayUtil.logOrderPay(logger, request, "通联支付结束确认  帐单已处理：" + detail.getBATCHID());
                    AllinPayUtil.logOrderPay(logger, request, "通联支付结束处理结束");

                    if (!PayContext.getContext().isFromNotify()) {
                        ValidationResult validationResult = new ValidationResult(ValidationResultCode.VALIDATION_ERROR_ALLINPAY_HANDLED);
                        PayContext.getContext().setValidationResult(validationResult);
                    }
                    return;
                }
            }

        }

        //使用通联账单进行判断
        //实时和批量处理

        if(SysStringUtils.isEmpty(request.getBatchTransRequestCode()))
        {
            handleRealTimePay(response);
        } else
        {
            handleBatchPay(response);
        }
        AllinPayUtil.logOrderPay(logger, request, "通联支付结束处理结束");

    }

    private void handleRealTimePay(AllinPayResponse response)
    {
        PayRequest request=PayContext.getContext().getPayRequest();


        Integer state=OrderPayState.STATE_UNKNOWN;

        if (PayContext.getContext().isSuccess()) {
            //如果成功，通联订单再确认一下


            if(AllinPayResultCode.isSuccess(response.getINFO().getRET_CODE()))
            {
                state=OrderPayState.STATE_SUCCESS;
            } else
            {
                state=OrderPayState.STATE_REMOTE_PROCESSING;

            }
            orderPayStateService.markState(request, state);
        }
        else
        {
            String retCode=PayContext.getContext().getRetCode();

            if (AllinPayResultCode.isMiddleCode(retCode))
            {
                state=OrderPayState.STATE_REMOTE_PROCESSING;
            } else
            {
                state=OrderPayState.STATE_FAIL;

            }
            orderPayStateService.markState(request, state);
        }
    }

    private void handleBatchPay(AllinPayResponse response)
    {
        PayRequest request=PayContext.getContext().getPayRequest();


        Integer state=OrderPayState.STATE_UNKNOWN;

        String retCode=response.getINFO().getRET_CODE();
        if (AllinPayResultCode.isSuccess(retCode)) {
            //如果成功，通联订单再确认一下
            state=OrderPayState.STATE_SUCCESS;
            orderPayStateService.markState(request, state);
        }
        else
        {
            if (AllinPayResultCode.isMiddleCode(retCode))
            {
                state=OrderPayState.STATE_REMOTE_PROCESSING;
            } else
            {
                state=OrderPayState.STATE_FAIL;

            }
            orderPayStateService.markState(request, state);
        }
    }


    @Override
    public void internalValidate(ValidationResult result,PayRequest request) {
        super.internalValidate(result, request);
    }
}
